var express = require("express");
var router = express();
// var request = require("request");
// var jwt = require("jsonwebtoken");
var db = require("../config/mysql");
var vertoken = require("../config/token");
// var { appid, appSecret } = require("../config/wx");
const multer = require("multer");

// 过滤文件，只能上传图片
var fileFilter = function (req, file, cb) {
  var acceptableMime = ["image/jpeg", "image/png", "image/jpg", "image/gif"];
  // 限制类型
  // null是固定写法
  if (acceptableMime.indexOf(file.mimetype) !== -1) {
    cb(null, true); // 通过上传
  } else {
    // 不符合规则，拒绝文件并且直接抛出错误
    cb(null, false); // 禁止上传
    cb(new Error("文件类型错误"));
    // cb("Error: Images Only!");
  }
};

// 定义上传文件路径 和 名字
var path = require("path");
var storage = multer.diskStorage({
  //设置 上传图片服务器位置
  destination: path.resolve(__dirname, "../uploads/image"),
  //设置 上传文件保存的文件名
  filename: function (req, file, cb) {
    // 获取后缀扩展
    let extName = file.originalname.slice(file.originalname.lastIndexOf(".")); //.jpg
    // 获取名称
    let fileName = Date.now();
    console.log(fileName + parseInt(Math.random() * 9999) + extName); //时间戳+随机数生成文件名
    cb(null, fileName + parseInt(Math.random() * 9999) + extName);
  },
});

var limits = {
  fileSize: 1024 * 500, //设置限制（可选）
};

//单张上传
// var multer = require("multer");
const imageUploader = multer({
  // fileFilter,
  storage,
  // limits,
}).single("file"); //文件上传预定 name 或者 字段
// --------------------------------------------------二选一
//多张上传
// var multer = require("multer");
// const imageUploader = multer({
//   fileFilter,
//   storage,
//   limits,
// }).array("file");

//以上三个字段是固定写法

/**
 * @api {post} /api/admin/upload 文件上传
 * @apiDescription 文件上传
 * @apiName upload
 * @apiGroup Admin
 * @apiParam {form-data} file 文件
 *
 * @apiSampleRequest api/admin/upload
 *
 */
router.post("/upload", (req, res, err) => {
  imageUploader(req, res, function (err) {
    // console.log(err);
    if (err) {
      // return res.end("Error uploading file.");
      return res.json({
        status: false,
        msg: err.message,
      });
    }
    const file = req.file;
    // file.url = `http://localhost:3000/uploads/${file.filename}`;
    // console.log(req.file);
    // console.log(`http://localhost:3000/uploads/image/${file.filename}`);
    // res.redirect(req.baseUrl);
    res.json({
      status: true,
      url: `http://localhost:3000/uploads/image/${file.filename}`,
      msg: "上传成功",
    });
  });
});

/**
 * @api {post} /api/admin/login 管理员登录
 * @apiDescription 管理员登录
 * @apiName login
 * @apiGroup Admin
 * @apiParam {Sting} username 用户名
 * @apiParam {Sting} password 用户密码
 *
 * @apiSampleRequest api/admin/login
 *
 */
router.post("/login", function (req, res) {
  var { username, password } = req.body;
  // 查询账户数据
  var sql = `SELECT * FROM admin WHERE username = ? AND password = ? `;
  db.query(sql, [username, password], function (results, fields) {
    if (results.length) {
      if (
        results[0].username === username &&
        results[0].password === password
      ) {
        vertoken.setToken(username, results[0].id).then((data) => {
          res.json({
            status: true,
            token: data,
            msg: "登录成功",
          });
        });
      }
    } else {
      res.json({
        status: false,
        msg: "登录失败",
      });
    }
  });
});

/**
 * @api {get} /api/admin/users 管理员成员列表
 * @apiDescription 管理员成员列表
 * @apiName users
 * @apiGroup Admin
 *
 * @apiSampleRequest api/admin/users
 *
 */

router.get("/users", function (req, res) {
  var sql = `SELECT * FROM admin`;
  db.query(sql, [], function (results, fields) {
    if (results.length) {
      res.json({
        status: true,
        data: results,
        msg: "获取成功",
      });
    } else {
      res.json({
        status: false,
        msg: "获取失败",
      });
    }
  });
});

/**
 * @api {get} /api/admin/menu 后台菜单
 * @apiDescription 后台菜单
 * @apiName menu
 * @apiGroup Admin
 *
 * @apiSampleRequest api/admin/menu
 *
 */

router.get("/menu", function (req, res) {
  var sql = `SELECT * FROM system_menu`;
  var menuTile = [];
  var menuChild = [];
  db.query(sql, [], function (results, fields) {
    if (results.length) {
      results.forEach((element) => {
        if (element.pid === 0) {
          results.forEach((ele) => {
            if (ele.pid === element.id) {
              menuChild.push(ele);
            }
          });
          menuTile.push({ authName: element.title, children: menuChild });
          menuChild = [];
        }
      });
      res.json({
        status: true,
        data: menuTile,
        msg: "获取成功",
      });
    } else {
      res.json({
        status: false,
        msg: "获取失败",
      });
    }
  });
});

/**
 * @api {post} /api/admin/addsong 添加歌曲
 * @apiDescription 添加歌曲
 * @apiName addsong
 * @apiGroup Admin
 *
 * @apiParam name 歌曲名称
 * @apiParam artist 歌手
 * @apiParam pic 歌曲图片
 * @apiParam musicurl 歌曲文件
 *
 * @apiSampleRequest api/admin/addsong
 *
 */

router.post("/addsong", function (req, res) {
  var { name, artist, pic, musicurl, introduction } = req.body;
  // console.log(req.body);
  var sql = `
  INSERT INTO songs (
    id,
    name,
    artist,
    rid,
    pic,
    score100,
    hasLossless,
    releaseDate,
    album,
    albumid,
    artistid,
    songTimeMinutes,
    pic120,
    musicurl,
    lrcUr,
    introduction 
  )
  VALUES
    (
      NULL,
      ?,
      ?,
      NULL,
      ?,
      NULL,
      NULL,
      NULL,
      NULL,
      NULL,
      NULL,
      NULL,
      NULL,
      ?,
      NULL,
      ?
    )
  `;
  if (name !== "") {
    db.query(
      sql,
      [name, artist, pic, musicurl, introduction],
      function (results, fields) {
        // console.log(results);
        if (results.affectedRows > 0) {
          res.json({
            status: true,
            id: results.insertId,
            msg: "添加成功",
          });
        } else {
          res.json({
            status: false,
            msg: "添加失败",
          });
        }
      }
    );
  }
});

/**
 * @api {post} /api/admin/song/update 通过id更改歌曲
 * @apiDescription 通过id更改歌曲
 * @apiName songUpdate
 * @apiGroup Admin
 *
 * @apiParam {id} id 歌曲id
 *
 * @apiSampleRequest api/admin/song/update
 *
 */

router.post("/song/update", function (req, res) {
  const { name, artist, pic, musicurl, introduction, id } = req.body;
  var sql = `
  UPDATE songs 
  SET name = ?,
  artist = ?,
  pic = ?,
  musicurl = ?, 
  introduction = ?
  WHERE
	  songs.id = ?
  `;
  db.query(
    sql,
    [name, artist, pic, musicurl, introduction, id],
    function (results, fields) {
      if (results.affectedRows > 0) {
        res.json({
          status: true,
          data: results,
          msg: "获取成功",
        });
      } else {
        res.json({
          status: false,
          msg: "获取失败",
        });
      }
    }
  );
});

/**
 * @api {post} /api/admin/song/delete 通过id删除歌曲
 * @apiDescription 通过id删除歌曲
 * @apiName songDelDelete
 * @apiGroup Admin
 *
 * @apiParam {id} id 歌曲id
 *
 * @apiSampleRequest api/admin/song/delete
 *
 */

router.post("/song/delete", function (req, res) {
  const { id } = req.body;
  var sql = `
  DELETE 
  FROM
    songs 
  WHERE
	  songs.id = ?
  `;
  db.query(sql, [id], function (results, fields) {
    if (results.affectedRows > 0) {
      res.json({
        status: true,
        data: results,
        msg: "删除成功",
      });
    } else {
      res.json({
        status: false,
        msg: "删除失败",
      });
    }
  });
});

module.exports = router;
